<template>
    <!-- 搜索相关 start -->
    <el-form :model="queryParams" ref="refForm" size="default" :inline="true" v-show="showSearch" label-width="58px">
        <el-form-item label="合集名称" prop="collectionName" label-width="75px">
            <el-input v-model="queryParams.collectionName" placeholder="请输入合集名称" clearable
                @keyup.enter.native="handleGetList" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="default" @click="handleGetList">搜索</el-button>
            <el-button type="primary" icon="el-icon-refresh" size="default" @click="resetForm(refForm)">重置</el-button>
        </el-form-item>
    </el-form>
    <!-- 搜索相关 end -->

    <!-- 操作相关 start -->
    <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="default"
                @click="outerVisible = true; addOrUpdate = true; title = '新增合集'">新增</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="default" @click="handleUpdate"
                :disabled="true">修改</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="default" @click="handleDeleteConfirmEvent"
                :disabled="true">删除</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="default" :disabled="true">导出</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-button type="info" plain icon="el-icon-s-operation" size="default" :disabled="true">日志</el-button>
        </el-col>
        <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="handleGetList"></right-toolbar> -->
    </el-row>
    <!-- 操作相关 end -->

    <!-- 表格相关 start -->
    <el-table :data="filterTableData" style="height: 550px;">
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" width="55" :index="indexMethod" />
        <el-table-column label="合集名称" prop="collectionName" width="120" show-overflow-tooltip />
        <el-table-column label="合集" prop="wxAvatar" width="100">
            <template #default="scope">
                <el-image style="width: 100px; height: 100px; z-index: 2000;" :src="scope.row.coverFilePreviewUrl"
                    :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="scope.row.fileUrlList"
                    :initial-index="4" fit="cover" :preview-teleported="true" />
            </template>
        </el-table-column>
        <el-table-column width="350">
            <template #header>
                <el-input v-model="search" size="small" placeholder="Type to search" />
            </template>
            <template #default="scope">
                <el-tooltip content="默认使用合集里的第一张照片作为封面！" placement="top" :enterable="false" :open-delay="1000">
                    <el-button type="primary" v-if="!scope.row.menuSetted"
                        @click="collectionCoverPicSetting(scope.$index, scope.row)">设置封面</el-button>
                </el-tooltip>
                <el-tooltip content="设置合集里的照片" placement="top" :enterable="false" :open-delay="1000">
                    <el-button type="primary" v-if="!scope.row.menuSetted"
                        @click="collectionPicSetting(scope.$index, scope.row)">设置照片</el-button>
                </el-tooltip>
                <el-button type="primary" :icon="Edit" @click="handleEdit(scope.$index, scope.row)" />
                <!-- <template #default="scope"> -->
                <el-popconfirm width="220" confirm-button-text="确定" cancel-button-text="取消" :icon="InfoFilled"
                    icon-color="#626AEF" title="确定删除此合集么？" @confirm="handleDeleteConfirmEvent(scope.$index, scope.row)">
                    <template #reference>
                        <el-button type="primary" :icon="Delete" />
                    </template>
                </el-popconfirm>
                <!-- </template> -->
            </template>
        </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100, 200, 300, 400]" :small="small" :disabled="disabled" :background="background"
        layout="total, sizes, prev, pager, next, jumper" :total=pageData.totalNum @size-change="handleSizeChange"
        @current-change="handleCurrentChange" style="margin-top: 20px;" />
    <!-- 表格相关 end -->

    <!-- 添加或修改参数配置对话框 start-->
    <el-dialog :title="title" width="600px" append-to-body draggable v-model="outerVisible">
        <el-row :gutter="15">
            <el-form :model="addFormData" :rules="rules" :size="formSize" label-width="150px" ref="addFormRef"
                style="max-width: 600px">
                <el-col :span="24">
                    <el-form-item label="合集名称" prop="collectionName">
                        <el-input v-model="addFormData.collectionName" placeholder="请输入合集名称"
                            :autosize="{ minRows: 4, maxRows: 4 }" :style="{ width: '100%' }"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item size="large">
                        <el-button type="primary" @click="submitAddForm(addFormRef)">{{ addOrUpdate ? '保存' : '修改'
                            }}</el-button>
                        <el-button @click="outerVisible = false">取消</el-button>
                        <el-button @click="resetForm(addFormRef)">重置</el-button>
                    </el-form-item>
                </el-col>
            </el-form>
        </el-row>
    </el-dialog>
    <!-- 添加或修改参数配置对话框 end -->

    <!-- 配置合集照片对话框 start-->
    <el-dialog :title="collectionSettingTitle" width="750px" height="200px" lock-scroll :overflow="false" append-to-body
        draggable v-model="collectionSettingOuterVisible" v-if="collectionSettingOuterVisible">
        <Suspense>
            <template #default>
                <FileList :fileListSinglePage="false" :userId="currentUserId"
                    :selectedFileIdList="currentSelectedFileIdList" :albumCollectionId="currentAlbumCollectionId"
                    :isCoverFile="isCoverFile">
                </FileList>
            </template>
        </Suspense>
    </el-dialog>
    <!-- 配置合集照片对话框 end -->
</template>
<script lang="ts" setup>
import { computed, ref, reactive, onMounted, defineAsyncComponent } from 'vue'
import { showErrorMsg, showSuccessMsg, resetForm } from '@/api/common';
import type { ApiResponse, PageResponse, OnlyIdRequest} from '@/api/common'
import type { FormInstance, FormRules, ComponentSize } from 'element-plus'
import { Delete, Edit, InfoFilled } from '@element-plus/icons-vue'
import { addAlbum, updateAlbum, deleteAlbum, page, listAllFileId, getPreviewFileId } from "@/api/albumCollection/albumCollection";
import type { QueryParams, AlbumPageData, Album, PageData, AlbumAddRequest, SelectedFileIdListResponse, SelectedCoverFileIdResponse } from '@/api/albumCollection/albumCollection';
// import FileList from '../file/FileList.vue';
const FileList = defineAsyncComponent(() => import('@/views/file/FileList.vue'))
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
let title = ref('新增相册')
let collectionSettingTitle = ref('相册配置')
let outerVisible = ref(false)
let collectionSettingOuterVisible = ref(false)
// const autoCreateTask = ref(true)
// 显示搜索条件
let showSearch = ref<boolean>(true)
const refForm = ref<FormInstance>()
// 默认新增
let addOrUpdate = ref<boolean>(true);
let onlyIdRequest = reactive<OnlyIdRequest>({
    id: 1,
})
let pageData = reactive<PageData>({
    totalNum: 0,
    tableData: [],
})
let queryParams = reactive<QueryParams>({
    pageNum: 1,
    pageSize: 10,
    collectionName: '',
})
const fileIdRequest = reactive<OnlyIdRequest>({
    id: null,
})
const search = ref('')
const filterTableData = computed(() =>
    pageData.tableData.filter(
        (data) =>
            !search.value ||
            data.collectionName.toLowerCase().includes(search.value.toLowerCase())
    )
)
const indexMethod = (index: number) => {
    return index + 1
}
const handleEdit = (index: number, row: Album) => {
    addFormData.id = row.id;
    addFormData.collectionName = row.collectionName;
    addOrUpdate.value = false;
    title.value = '修改合集名称'
    outerVisible.value = true;
}
const handleDeleteConfirmEvent = (index: number, row: Album) => {
    onlyIdRequest.id = row.id;
    deleteAlbum(onlyIdRequest).then((res: ApiResponse<string>) => {
        if (res.status != 200) {
            showErrorMsg(res.msg);
        } else {
            showSuccessMsg("删除成功")
            outerVisible.value = false;
            handleGetList();
        }
    });
}
let currentUserId = ref<number>(-1);
let currentSelectedFileIdList = ref<number[]>([])
let currentAlbumCollectionId = ref<number>(-1)
let isCoverFile = ref<boolean>(false)
// 配置封面照片
const collectionCoverPicSetting = (index: number, row: Album) => {
    fileIdRequest.id = row.id;
    getPreviewFileId(fileIdRequest).then((res: SelectedCoverFileIdResponse) => {
        if (res.status != 200) {
            showErrorMsg(res.msg);
        } else {
            currentSelectedFileIdList.value = [];
            if (res.data) {
                currentSelectedFileIdList.value.push(res.data);
            }
            currentAlbumCollectionId.value = row.id;
            isCoverFile.value = true;
            collectionSettingOuterVisible.value = true;
        }
    });
}
// 配置合集照片
const collectionPicSetting = (index: number, row: Album) => {
    fileIdRequest.id = row.id;
    listAllFileId(fileIdRequest).then((res: SelectedFileIdListResponse) => {
        if (res.status != 200) {
            showErrorMsg(res.msg);
        } else {
            if (res.data) {
                currentSelectedFileIdList.value = [];
                res.data.forEach(r => {
                    currentSelectedFileIdList.value.push(r);
                })
                currentAlbumCollectionId.value = row.id;
                console.log("manage currentSelectedFileIdList:", currentSelectedFileIdList.value);

                isCoverFile.value = false;
                collectionSettingOuterVisible.value = true;
            }
        }
    });
}
const handleSizeChange = (newSize: number) => {
    // console.log(`${newSize} items per page`)
    queryParams.pageSize = newSize;
    handleGetList();
}
const handleCurrentChange = (newPage: number) => {
    // console.log(`current page: ${newPage}`)
    queryParams.pageNum = newPage;
    handleGetList();
}
const handleUpdate = (row: Album) => {
    // console.log(row.id)
}
const handleGetList = () => {
    page(queryParams).then((res: ApiResponse<PageResponse<AlbumPageData>>) => {
        if (res.status != 200) {
            showErrorMsg(res.msg);
        } else {
            let totalTemp = parseInt(res.data.total);
            pageData.totalNum = totalTemp;
            pageData.tableData = res.data.records;
        }
    });
}
onMounted(() => {
    handleGetList();
})
const addFormRef = ref<FormInstance>()
const formSize = ref<ComponentSize>('default')
let addFormData = reactive<AlbumAddRequest>({
    id: null,
    collectionName: '',
})
let rules = reactive<FormRules<AlbumAddRequest>>({
    collectionName: [{
        required: true,
        message: '请输入合集名称',
        trigger: 'change'
    }],
})
const submitAddForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (addOrUpdate.value) {
                addFormData.id = null;
                addAlbum(addFormData).then((res: ApiResponse<string>) => {
                    if (res.status != 200) {
                        showErrorMsg(res.msg);
                    } else {
                        showSuccessMsg("新增成功");
                        outerVisible.value = false;
                        handleGetList();
                    }
                })
            } else {
                updateAlbum(addFormData).then((res: ApiResponse<string>) => {
                    if (res.status != 200) {
                        showErrorMsg(res.msg);
                    } else {
                        showSuccessMsg("修改成功");
                        outerVisible.value = false;
                        handleGetList();
                    }
                })
            }

        } else {
            console.log('error submit!', fields)
        }
    })
}
</script>
<style>
.custom-loading,
.custom-error,
.custom-empty {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    width: 100%;
}

.spinner {
    border: 4px solid rgba(0, 0, 0, 0.1);
    width: 36px;
    height: 36px;
    border-radius: 50%;
    border-top-color: #333;
    animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
    to {
        transform: rotate(360deg);
    }
}
</style>